<!DOCTYPE HTML>
<html class="x-admin-sm">
<head>
    <th:block th:insert="~{head/head :: common_head}"></th:block>
    <script type="text/javascript" th:src="@{/jsfiles/xm-select.js?t=20813}" charset="utf-8"></script>
</head>
<body style="background-color: white">
<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card" style="margin: 10px;">
                    <div class="layui-tab layui-tab-brief">
                        <div class="layui-tab-content" >
                            <div class="layui-tab-item layui-show">
                                <form class="layui-form layui-form-pane" autocomplete="off">
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">
                                            <span class='x-red'>*</span>所属区局：
                                        </label>
                                        <div class="layui-input-block">
                                            <div id="xzjg" name="xzjg" style="width: 403.8px"></div>
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <label class="layui-form-label">
                                            新网点名称：
                                        </label>
                                        <div class="layui-input-block">
                                            <input type="text" id="bjmc" name="bjmc" class="layui-input" style="width: 403.8px">
                                        </div>
                                    </div>
                                    <div class="layui-form-item">
                                        <button class="layui-btn" lay-submit="" lay-filter="*" id="bc">
                                            新增存盘
                                        </button>
                                    </div>
                                    <div style="height: 25px;"></div>
                                </form>
                                <div style="height:100px;"></div>
                            </div>

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
<th:block th:insert="~{head/head :: common_jsfiles}"></th:block>
<script>
    /**
     * lx 0 表示新增  1 表示修改 id 为主键
     * 所有增改页面，载入时，都是通过doFirst回调renderForm
     *
     */
    var lx="[[${lx}]]";
    var id="[[${id}]]";
    var jd="[[${jd}]]";
    var wd="[[${wd}]]";
    var name="[[${name}]]";
    var url ="[[${serverUrl}]]/zhdt/wdzb/";
    var ms = "wdzb_info";

    $(document).ready(function() {
        $("#bjmc").val(name);
        if(lx=="1"){
            $("#bc").html("修改存盘");
        }else{
            $("#bc").html("新增存盘")
        }
    });


    function on_result(result)
    {
        if (result.code!=500)
        {
            if (result.code==1 || result.code==2){
                //新增成功
                layer.msg(result.msg, { time: 1000 }, function() {
                    window.parent.on_done();
                });
            } else {
                layer.msg(result.msg);
                $('#bc').removeClass("layui-btn-disabled").attr("disabled",false);
            }
        }
        else
        {
            layer.msg(result.msg);
            $('#bc').removeClass("layui-btn-disabled").attr("disabled",false);
        }
    }

    var xzjg;
    var zbfl;
    //表单相关
    layui.use(['form'], function(){
        var form = layui.form;

        //渲染表格参数
        var renderForm = function (formData){
            console.info("formData:"+JSON.stringify(formData));

            if (lx==1){
                console.info("查询得到的数据:"+JSON.stringify(formData));
                $("#bjmc").val(formData.zhdtWdzb.name);
            }

            xzjg = xmSelect.render({
                el: '#xzjg',
                autoRow: true,
                radio: true,
                clickClose: true,
                filterable: true,
                filterDone: function(val, list) {
                    const self = this; // 组件实例
                    const expandValues = []; // 收集需要展开的节点value

                    // 1. 递归收集所有节点的value（包括所有层级）
                    function collectExpandKeys(node) {
                        expandValues.push(node.value); // 收集当前节点
                        if (node.children && node.children.length) {
                            node.children.forEach(child => collectExpandKeys(child)); // 递归收集子节点
                        }
                    }
                    // 遍历筛选后的list，收集所有节点
                    list.forEach(node => collectExpandKeys(node));

                    xzjg.changeExpandedKeys(expandValues);

                    // 3. 打印清理后的筛选结果（避免循环引用报错）
                    const cleanList = list.map(node => ({
                        name: node.name,
                        value: node.value,
                        children: node.children ? node.children.map(child => ({
                            name: child.name,
                            value: child.value
                        })) : []
                    }));
                    console.log('筛选结果：', cleanList);
                    console.log('通过expandedKeys展开的节点：', expandValues);
                },
                tree: {
                    show: true,
                    showFolderIcon: true,
                    showLine: true,
                    indent: 20,
                    strict: false,
                    expandedKeys: [-3], // 初始展开节点（符合官方配置）
                },
                toolbar: { show: true, list: ['ALL', 'REVERSE', 'CLEAR'] },
                height: 'auto',
                data: () => formData.tXzjgTree
            });

            form.render(); // 重新渲染
        }

        //表单数据初始化
        function doFirst()
        {
            //发送的请求
            var jsonData = {
                id: id,
                lx: lx,
                timestamp:new Date().getTime()
            };
            var sendStr = {
                data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a"),localStorage.getItem("b"))
            };
            post_json_form(url+"info1",JSON.stringify(sendStr),"数据加载中...",renderForm);
        }

        //提交逻辑
        function onSave(nonce_zhi){
            //获取提交令牌
            if (is_null(nonce_zhi)){
                $('#bc').removeClass("layui-btn-disabled").attr("disabled",false);
                layer.msg("没有获取到操作凭证！请重试！",{icon:2,anim:6});
                return false;
            }

            var xzjgId = xzjg.getValue('valueStr');

            var jsonData = {
                xzjg: xzjgId,
                bjmc: $("#bjmc").val(),
                jd:jd,
                wd:wd,
                lx: lx,
                id:id||'',
                nonce_ms:ms,
                nonce_zhi:nonce_zhi,
                timestamp:new Date().getTime()
            };
            var sendStr = {
                data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a"),localStorage.getItem("b"))
            };
            post_json_token(url+"save1",JSON.stringify(sendStr),"数据提交中...");
        }

        //监听提交
        form.on('submit(*)', function(data){
            if ($("#bjmc").val()==""){
                layer.msg("请输入标记名称！",{icon:2,anim:6});
                init('bjmc');
                return false;
            }
            if (!confirm("确定提交存盘？")) return false;
            $('#bc').addClass("layui-btn-disabled").attr("disabled",true);
            psot_get_nonce(ms,"[[${serverUrl}]]/getnonce",onSave)
            return false;
        });

        // 为所有带有lay-event属性的元素添加事件监听
        $(document).on('click', '[lay-event]', function(obj){
            var eventName = $(this).attr('lay-event'); // 获取事件名称
            if(eventName === 'sc'){
                if (!confirm("确定删除分组信息？")) return false;
                var jsonData = {
                    lx: lx,
                    id: id,
                    timestamp:new Date().getTime()
                };
                var sendStr = {
                    data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a"),localStorage.getItem("b"))
                };
                post_json_token(url+"del",JSON.stringify(sendStr),"数据删除中...");
                return false;
            } else if(eventName === 'xj'){
                window.location.href="info?lx=0&id="+id+"&pid="+id+"";
                return false;
            } else if(eventName === 'qy'){
                $("#jgqy_div").show();
                return false;
            } else if(eventName === 'qdqy'){
                if($("#new_pid").val()==""){
                    layer.msg("没有选择新的上级分组！",{icon:2,anim:6});
                    init_select('new_pid');
                    return false;
                }
                if (!confirm("确定变更上级？如果有下级，会一起迁移至新的上级！")) return false;
                var newPid = qysj.getValue('valueStr');
                var jsonData = {
                    lx: lx,
                    id: id,
                    new_pid: newPid,
                    timestamp:new Date().getTime()
                };
                var sendStr = {
                    data:encrypt_str(JSON.stringify(jsonData),localStorage.getItem("a"),localStorage.getItem("b"))
                };
                post_json_token(url+"qy",JSON.stringify(sendStr),"数据迁移中...");
                return false;
            }
        });

        //首先执行
        doFirst();
    });
</script>
</body>
</html>